package swing.frame.whiteboard;

import api.BoardServer;
import beans.Whiteboard;
import client.UserSession;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syuchen.boardserver.protocol.WbResponse;
import com.syuchen.client.udp.UdpSocketPool;
import swing.frame.ChatFrame;
import utils.CommonUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

/**
 * @author ywjia
 */
public class MyDrawPanel extends JFrame {

    private Thread acceptDataThread;
//    private Thread heartbeatThread;
//    public DatagramSocket datagramSocket;
    public Whiteboard whiteboard;
    StaffPanel sp=new StaffPanel();
    DrawPanel dp=new DrawPanel();
    ToolsPanel tp=new ToolsPanel();
    ColorPanel cp=new ColorPanel();
    ChatFrame chatFrame;
    boolean isAdmin;
    boolean isResizeable;
    String groupName;

    public static void main(String[] args) {

        MyDrawPanel myDrawPanel=new MyDrawPanel();
        myDrawPanel.init();
    }

    public MyDrawPanel() {

    }

    public MyDrawPanel(Whiteboard whiteboard, boolean isAdmin,String groupName) {
        this.whiteboard = whiteboard;
        this.isAdmin = isAdmin;
        this.groupName=groupName;
        this.isResizeable=false;
        this.init();
        this.initChatFrame();
        this.initConnect();
    }

    private void initChatFrame() {
        chatFrame = new ChatFrame(this);
        chatFrame.setLocation(this.getX() + this.getWidth(), this.getY());
        chatFrame.showFrame();
        this.addComponentListener(new ComponentAdapter(){
            @Override
            public void componentMoved(ComponentEvent e) {
                super.componentMoved(e);
                chatFrame.setLocation(getX() + 1300, getY());
            }
        });
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowIconified(WindowEvent e) {
                super.windowIconified(e);
                chatFrame.hideFrame();
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
                super.windowDeiconified(e);
                chatFrame.showFrame();
            }

//            @Override
//            public void windowActivated(WindowEvent e) {
//                super.windowActivated(e);
//                chatFrame.toFront();
//                System.out.println("激活" + chatFrame.isActive());
//            }
        });
    }

    private void initConnect() {
        BoardServer.boardService.connectBoard(UserSession.LoginUser(), whiteboard.getId());
        acceptDataThread = new Thread(() -> {
            //白板连接后循环接收服务器发送过来的数据包，解析数据包然后更新白板
            while (true) {
                try {
                    String msg = UdpSocketPool.takeMsg();
                    JSONObject jsonObject = JSON.parseObject(msg);
                    WbResponse wbResponse = JSON.toJavaObject(jsonObject, WbResponse.class);
                    handleResponse(wbResponse);
                } catch (InterruptedException e) {
                    UdpSocketPool.stopMsg();
                    break;
                }
            }
        });
        acceptDataThread.start();
    }

    private void handleResponse(WbResponse wbResponse) {
        switch (wbResponse.getCode()) {
            case WbResponse.MSG_CODE :
                JOptionPane.showMessageDialog(this, wbResponse.getResult());
                break;
            case WbResponse.LOAD_BOARD_CODE :
                List<String> loadShapeList = CommonUtils.convertJsonToList(wbResponse.getResult().toString(), String.class);
                dp.update(loadShapeList, true);
                break;
            case WbResponse.FLUSH_MEMBERS_CODE :
                List<String> memberList = CommonUtils.convertJsonToList(wbResponse.getResult().toString(), String.class);
                sp.setMembersList(memberList);
                break;
            case WbResponse.UPDATE_BOARD_CODE :
                List<String> updateShapeList = CommonUtils.convertJsonToList(wbResponse.getResult().toString(), String.class);
                dp.update(updateShapeList, false);
                break;
            case WbResponse.CLEAR_BOARD_CODE:
                JOptionPane.showMessageDialog(this, wbResponse.getResult());
                dp.clearBoard();
                break;
            case WbResponse.CHAT_MESSAGE_CODE :
                chatFrame.flushMessage(wbResponse.getResult().toString());
                break;
            default:
        }
    }

    public void init(){
        
        this.setTitle(groupName+"——"+whiteboard.getBoard_name());
        this.setSize(1300,800);
        this.setResizable(isResizeable);
        //将窗体设置在中间位置
        this.setLocationRelativeTo(null);
        //设置关闭按钮
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        //设置布局方式
        this.setLayout(new BorderLayout());
        //创建画板
        MenuPanel mp=new MenuPanel(this);
        if(!isAdmin) {
            mp.button1.setVisible(false);
            mp.button3.setVisible(false);
        }
        this.add(mp, BorderLayout.NORTH);
        this.add(tp,BorderLayout.WEST);
        this.add(dp,BorderLayout.CENTER);
        this.add(cp,BorderLayout.SOUTH);
        this.add(sp,BorderLayout.EAST);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosed(e);
                chatFrame.dispose();
                if(isAdmin){
                    int i=JOptionPane.showConfirmDialog(dp,"是否要进行保存？","保存提示",2,1);
                    if(i==0){
                        BoardServer.boardService.saveBoard(whiteboard.getId());
                    }
                }
                BoardServer.boardService.disconnectBoard(UserSession.LoginUser(),whiteboard.getId());
//                BoardApi.disconnect_board(datagramSocket,UserSession.LoginUser(),whiteboard.getId());
//                heartbeatThread.stop();
                acceptDataThread.interrupt();
//                datagramSocket.close();
            }
        });
        this.setVisible(true);

        DrawListener dl=new DrawListener(tp,cp,dp,mp, this);

        dp.addMouseListener(dl);
        //添加面板鼠标的监听器
        dp.addMouseMotionListener(dl);



    }
}
